package com.kaibes.module.api.client;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.kaibes.core.base.util.StringUtils;
import com.kaibes.module.nacos.NacosOneListener;
import com.kaibes.web.api.ApiLinkService;

@Component
public class ApiServiceListener extends NacosOneListener implements InitializingBean {
    
    @Value("${kaibes.module.api.client.service-name}")
    private String serviceName;
    @Value("${spring.cloud.nacos.discovery.group:DEFAULT_GROUP}")
    private String group;
    @Value("${spring.application.name:}")
    private String service;
    @Autowired
    private ApiClient apiClient;
    @Autowired
    private ApiLinkService apiLinkService;
    
    @Override
    public String getName() {
        String[] fs = serviceName.split("//");
        String[] ss = fs[1].split(":");
        return ss[0];
    }

    @Override
    public String getGroup() {
        return group;
    }
    
    @Override
    public void onOneInstance() {
        apiClient.post(service, apiLinkService.listApi());
    }

	@Override
	public void afterPropertiesSet() throws Exception {
		if (StringUtils.isBlank(service)) {
            throw new RuntimeException("请配置服务名称${spring.application.name}！");
        }
        if (StringUtils.isBlank(serviceName)) {
            throw new RuntimeException("请配置API服务名称${kaibes.module.api.client.service-name}！");
        }
	}
    
}
